package com.fragrance.util;


import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Encrypt
{
  public static String MD5(String input)
  {
    return MD5(input, Charset.defaultCharset());
  }

  public static String MD5(String input, String charset)
  {
    return MD5(input, Charset.forName(charset));
  }

  public static String MD5(String input, Charset charset)
  {
    MessageDigest md = null;
    try
    {
      md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    md.update(input.getBytes(charset));

    char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
      'a', 'b', 'c', 'd', 'e', 'f' };
    byte[] tmp = md.digest();
    char[] str = new char[32];

    int k = 0;
    for (int i = 0; i < 16; i++) {
      byte byte0 = tmp[i];
      str[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
      str[(k++)] = hexDigits[(byte0 & 0xF)];
    }

    String result = new String(str);

    return result;
  }
  

  public static String encrypt3DES(String input, String key)
  {
    return encrypt3DES(input, key, Charset.forName("GB2312"));
  }

  public static String encrypt3DES(String input, String key, Charset charset)
  {
    try
    {
      return Byte.byte2hex(Des.encrypt(input.getBytes(charset.name()), key.getBytes()));
    }
    catch (Exception localException) {
    }
    return "";
  }

  public static String decrypt3DES(String input, String key)
  {
    return decrypt3DES(input, key, Charset.forName("GB2312"));
  }

  public static String decrypt3DES(String input, String key, Charset charset)
  {
    try
    {
      return new String(Des.decrypt(Byte.hex2byte(input.getBytes()), key.getBytes()), charset.name());
    }
    catch (Exception localException) {
    }
    return "";
  }
  
  public static void main(String [] args) throws Exception{
	  String key = "adfwerDGetSDF";
	  String des=  Encrypt.encrypt3DES("666666", key);
	  System.out.println(des);
	  
	  String des2 = Encrypt.decrypt3DES(des,key);
	  System.out.println(des2);
	  
	  
  }
}